package com.delivery.aspect;

import com.delivery.anno.AutoFill;
import com.delivery.context.BaseContext;
import com.delivery.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;

/**
 * 1. 获取注解上的操作类型
 * 2. 获取当前登录用户id
 * 3. 为数据库操作对象填充创建时间、创建人、更新时间、更新人字段
 * 4. 为数据库操作对象填充更新时间、更新人字段
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Before("@annotation(com.delivery.anno.AutoFill)")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("自动填充");
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length > 0) {
            Object entity = args[0];
            switch(operationType) {
                case INSERT:{
                    entity.getClass().getMethod("setCreateTime", LocalDateTime.class).invoke(entity, LocalDateTime.now());
                    entity.getClass().getMethod("setCreateUser", Long.class).invoke(entity, BaseContext.getCurrentId());
                    entity.getClass().getMethod("setUpdateTime", LocalDateTime.class).invoke(entity, LocalDateTime.now());
                    entity.getClass().getMethod("setUpdateUser", Long.class).invoke(entity, BaseContext.getCurrentId());
                    break;
                }
                case UPDATE:{
                    entity.getClass().getMethod("setUpdateTime", LocalDateTime.class).invoke(entity, LocalDateTime.now());
                    entity.getClass().getMethod("setUpdateUser", Long.class).invoke(entity, BaseContext.getCurrentId());
                    break;
                }
                default:
                    break;
            }
        }
    }
}

